package com.qfedu.zy.utils;

import com.qfedu.zy.dao.PermissionDAO;
import com.qfedu.zy.dao.RoleDAO;
import com.qfedu.zy.dao.UserDAO;
import com.qfedu.zy.pojos.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    private RoleDAO roleDAO;
    @Autowired
    private PermissionDAO permissionDAO;

    private UserDAO userDAO;

    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    public String getName(){
        return "myRealm01";
    }

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User)principalCollection.iterator().next();
        int userId = user.getUserId();

        Set<String> roles = roleDAO.queryRolesByUserId(userId);

        Set<String> permissions = permissionDAO.queryPermissionByUserId(userId);


        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permissions);

        return null;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String password = new String(token.getPassword());

        String md5Pwd = new SimpleHash("MD5",password).toHex();

        User user = userDAO.queryUserByName(username);
        if(user == null){
            throw  new UnknownAccountException("账号不存在！");
        }else{
            if(!user.getUserPwd().equals(md5Pwd)){
                throw  new IncorrectCredentialsException("密码错误");
            }
        }
        return new SimpleAuthenticationInfo(user,password,getName());
    }
}
